package com.estar.integaration.Controller;


import com.estar.integaration.Helper.MaterialCalcHelper;
import com.estar.integaration.Service.*;
import com.estar.integaration.Util.MExcelUtil;
import com.estar.integaration.Util.Util;
import com.estar.integaration.entity.*;
import com.estar.integaration.entity.NoSQL.Res;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author YJL
 * @since 2021-11-18
 */
@RestController
@RequestMapping("/product-db")
public class ProductDbController {

  @Autowired
  ITechPushHistoryService techPushHistoryService;
  @Autowired
  IProductDbService productDbService;
  @Autowired
  IMaterialService materialService;
  @Autowired
  IMaterialVoService materialvoService;
  @Autowired
  IChildAcodeService childAcodeService;
  @Autowired
  IAcodeProductVoService acodeProductVoService;
  @Autowired
  IProductionScheduleService productionScheduleService;

  MaterialCalcHelper materialCalcHelper = new MaterialCalcHelper();


  //用于判断是否有重复外购件清单
  List<String> haveUploadTechList = new ArrayList<>();

  @Value("${spring.profiles.active}")
  private String mEnvironment;

  //上传文件
  @PostMapping("/importMaterialVO-Product")
  @ResponseBody
  public Res importExcel(HttpServletRequest request) throws Exception {

    //取出交期Hash->  <A码,交期>
    HashMap<String,Date> scheduleHash = getScheduleHashMap();
    //查重 SQL
    List<String> haveUploadFileNameList = techPushHistoryService.getAllFileName();
    //取出文件 http
    MultipartHttpServletRequest params =  (MultipartHttpServletRequest)request;
    List<MultipartFile> multipartFiles = params.getFiles("file");
    //紧急属性
    Boolean isUrgent =  params.getParameter("isUrgent" ).equals("isUrgent");
    Vector<String> multipartFilePath = new Vector<>();//上来的文件地址List
    String filePath = null;
    //插入历史记录的BatchList
    List<TechPushHistory> techPushHistoryList = new ArrayList<>();
    ProductMachineInfo productMachineInfo = null;
    Res returnRes = new Res();
    //取出文件写入本地，历史、地址信息 软记录
    for(MultipartFile file : multipartFiles){
        if(!file.isEmpty()){
          if( haveUploadFileNameList.contains(file.getOriginalFilename()) || haveUploadTechList.contains(file.getOriginalFilename())){
            return new Res("40000","存在重复文件");
          }
        }
        //防止快速点击
        haveUploadTechList.add(file.getOriginalFilename());
        String UID = Util.getUUID();
        filePath = Util.writeFile2Local(file,mEnvironment,UID);
        //拿到文件
        multipartFilePath.add(filePath);
        //入历史List等待productId入db
        techPushHistoryList.add(new TechPushHistory(UID,file.getOriginalFilename(),new Timestamp(System.currentTimeMillis()),filePath,null,isUrgent));
    }
    //正式解析
    for(String address : multipartFilePath){
      //解析出所有文件
      String info = "";
      try {
//        productMachineInfo =  MExcelUtil.parseExcel(address, MaterialVo.class, MExcelUtil.initMaterialVOHash(),4,0,productDbService,materialService,info);
        //解析Excel
        productMachineInfo = MExcelUtil.HparseExcel(address);
      }catch (Exception e){
        e.printStackTrace();
        haveUploadTechList.clear();
        //自定义异常
        return new Res("40005",e.getMessage());
      }
      //设置历史记录
      techPushHistoryList.get(multipartFilePath.indexOf(address)).setProductId(productMachineInfo.getProductDb().getId());
      try {
        //最终将文件添加进去
        returnRes = materialCalcHelper.insertwithCalc(productMachineInfo,scheduleHash,isUrgent);

      }catch (Exception e){

        haveUploadTechList.clear();

        //加入文件的未知错误
        return new Res("40003", "第" + String.valueOf(multipartFilePath.indexOf(address)+1) + "个文件出错");

      }

    }

    haveUploadTechList.clear();

    techPushHistoryService.saveBatch(techPushHistoryList);

    return returnRes;

  }

  /**
   * 排期取出形成Hash
   * @return
   */
  public HashMap<String,Date> getScheduleHashMap(){
    //查询出全部交期
    List<ProductionSchedule> productionScheduleList = productionScheduleService.selectAllPs();
    //转换成Hash
    HashMap<String,Date> scheduleHash = new HashMap<>();

    productionScheduleList.forEach( p -> scheduleHash.put(p.getACode(),p.getStandardComeTime()));

    return scheduleHash;

  }

}
